package com.wanghaixin.realm;

import com.wanghaixin.pojo.SysUser;
import com.wanghaixin.service.MenuService;
import com.wanghaixin.service.RoleService;
import com.wanghaixin.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Auther: 王海新
 * @Date: 2020/10/25 16:48
 * @Description:
 */

@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //得到用户名和密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)authenticationToken;
        String username = usernamePasswordToken.getUsername();
        if (usernamePasswordToken.getPassword() == null) {
            throw new UnknownAccountException("请输入密码");
        }
        String password = new String(usernamePasswordToken.getPassword());
        //数据库中取出此name的用户信息
        SysUser byUsername = sysUserService.findByUsername(username);
        //判断该用户是否存在
        if (byUsername == null) {
            throw new UnknownAccountException("账户不存在");
        }
        //判断该用户密码是否正确
        if ( !byUsername.getPassword().equals(password) ) {
            throw new IncorrectCredentialsException("密码不正确");
        }
        //判断此用户是否已被冻结
        if (byUsername.getStatus() == 0) {
            throw new LockedAccountException("账户被冻结");
        }
        //将数据封装到 上面要求返回值的实现类中
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(byUsername,password,this.getName());

        return info;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //完成认证，我们来做授权,此方法的参数就是我们的SysUser对象
        SysUser sysUser = (SysUser)principalCollection.getPrimaryPrincipal();
        Long userId = sysUser.getUserId();
        //用户的角色
        List<String> rolsByUserID = roleService.findRolsByUserID(userId);
        //用户的菜单权限
        List<String> permsByUserId = menuService.findPermsByUserId(userId);
        //将数据封装到返回类型的实现类中
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(rolsByUserID);
        info.addStringPermissions(permsByUserId);
        return info;
    }


}
